package client.gui;

import java.awt.KeyboardFocusManager;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import javax.swing.text.JTextComponent;

/**
 *
 * @author Tomaz Strazisnik
 * http://www.javalobby.org/java/forums/t17439.html
 */
public class TextSelector
{
  private static FocusHandler installedInstance;

  /**
   * Install an PropertyChangeList listener to the default focus manager
   * and selects text when a text component is focused.
   */
  public static void install()
  {
    //already installed
    if (installedInstance != null)
      return;

    installedInstance = new FocusHandler();

    KeyboardFocusManager kfm = KeyboardFocusManager.getCurrentKeyboardFocusManager();

    kfm.addPropertyChangeListener("focusOwner", (PropertyChangeListener) installedInstance);
  }

  public static void uninstall()
  {
    if (installedInstance != null)
    {
      KeyboardFocusManager kfm = KeyboardFocusManager.getCurrentKeyboardFocusManager();
      kfm.removePropertyChangeListener("focusOwner", installedInstance);
    }
  }

  private static class FocusHandler implements PropertyChangeListener {

    @Override
    public void propertyChange(PropertyChangeEvent evt)
    {
      if (evt.getNewValue() instanceof JTextComponent)
      {
          JTextComponent text = (JTextComponent) evt.getNewValue();
          //select text if the component is editable
          //and the caret is at the end of the text
          if (text.isEditable() && text.getDocument().getLength() == text.getCaretPosition())
              text.selectAll();
      }
    }
  }
}

